package Day04;

import sun.plugin2.os.windows.Windows;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Stringchuan {
    public static void main(String[] args) {
        private static int ticket = 100;
//对象有三个，此时得需要static，要不然共享数据得时候，会出现线程安全的问题
        private static Object obj = new Object();

        @Override
        public void run() {
            while(true){
                //正确的
//            synchronized (obj) {
                synchronized (Windows.class){  //此时类充当对象 //Class clazz = Windows.class
                    //错误的，因为此时this表示的是t1,t2,t3三个对象
//            synchronized (this) {
                    if (ticket > 0) {

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        System.out.println(getName() + ":卖票，票号为: " + ticket);
                        ticket--;
                    } else {
                        break;
                    }
                }
            }
        }

        while(true){
            synchronized (Windows1.class) {//若是使用this则有三个对象，t1,t2,t3，会出现线程安全的问题
                if (ticket > 0) {

                    try{
                        Thread.sleep(100);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":卖票，票号为: " + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
            synchronized (s1){
                s1.append("a");
                s2.append("1");

                try {//
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }//将这一串代码看出代码①
                //当执行到Thread.sleep(100);的时候，就会停留
                synchronized (s2){
                    s1.append("b");
                    s2.append("2");

                    System.out.println(s1);
                    System.out.println(s2);
                }
            }
            ServerSocket ss = new ServerSocket(10000);

            //监听客户端连接，返回一个Socket对象
            Socket s = ss.accept();

            //获取输入流，读数据，并把数据显示在控制台
            InputStream is = s.getInputStream();
            byte[] bys = new byte[1024];
            int len = is.read(bys);
            String data = new String(bys, 0, len);
            System.out.println("服务器：" + data);

            //给出反馈
            OutputStream os = s.getOutputStream();
            os.write("数据已经收到".getBytes());

            //释放资源
//        s.close();
            ss.close();
        }
    }
}

